//
//  FruitLoopsController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/20.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "FruitLoopsController.h"
#import "MJRefresh.h"
#import "FLService.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "AFNetworking.h"
#import "LoginViewController.h"
#import "EnlargeImageViewController.h"
#import "DataSingleton.h"
#import "OMOrderEmptyTableViewCell.h"
@interface FruitLoopsController ()<UITableViewDelegate,UITableViewDataSource,ShareListTableViewCellDelegate>
{
    int currentPage;
    int sizeCount;
    CGFloat cellHeight;
    CGFloat emptyCellHeight;


}




@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) FLService *service;
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, strong) FruitLoopsCell *cell2;;
@property (nonatomic, strong) DataSingleton *dataHandler;
@property (nonatomic, strong) OMOrderEmptyTableViewCell *emptyCell;


@end

@implementation FruitLoopsController



//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}


- (NSMutableArray *)dataArray {
    
    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataArray;
}



-(void)dealloc

{
    [[NSNotificationCenter defaultCenter]removeObserver:self];


}


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.service = [[FLService alloc] init];
    
    
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerRereshing) name:@"refreshShareListMethod" object:nil];
    
    [self creatUI];
    [self creatData];
    
}


-(void)creatUI
{

//    self.topView.hidden = YES;
    self.dataHandler = [DataSingleton sharedDataSingleton];
    self.view.backgroundColor = BACKGROUND1;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc]init];

    
    
//    self.tableView.estimatedRowHeight = 94.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
}


-(void)creatData
{
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
        [self.tableView addFooterWithTarget:self action:@selector(footerRereshing13)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.footerRefreshingText = @"正在帮你加载中";
    
    
    
    
}


- (void)headerRereshing {
    
    currentPage  = 1;
    sizeCount = 20;
    [self getDate];
}




- (void)getDate {


    [self getShareListByPage:currentPage size:sizeCount];
}



- (void)getShareListByPage:(int)page size:(int)size
{

    NSString *urlStr = [NSString stringWithFormat:@"%@get_fruit_frend_list",SERVER_ADDRESS3];
    
    NSDictionary *parmas = @{@"cur_page" : [NSString stringWithFormat:@"%d",page] , @"cur_size" : [NSString stringWithFormat:@"%d",size]};
    
   
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
       
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            NSArray *array = responseObject[@"data"][@"list"];
            
          
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:array];
            
      
            [self.tableView reloadData];
            [self.tableView headerEndRefreshing];
           
        }
        else
        {
            
            [self.tableView headerEndRefreshing];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataHandler removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
            }
        
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
          [self.view makeToast:@"请检查网络"];
          [self.tableView headerEndRefreshing];
        
    }];
    

}



-(void)footerRereshing13
{
    
    currentPage ++;
    sizeCount = 20;
    [self getDate2];
    
}


-(void)getDate2
{

     NSString *urlStr = [NSString stringWithFormat:@"%@get_fruit_frend_list",SERVER_ADDRESS3];
     NSDictionary *parmas = @{@"cur_page" : [NSString stringWithFormat:@"%d",currentPage] , @"cur_size" : [NSString stringWithFormat:@"%d",sizeCount]};
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            NSArray *array = responseObject[@"data"][@"list"];
            
            if (array.count == 0) {
                
                self.tableView.footerReleaseToRefreshText = @"暂无更多数据";
                self.tableView.footerRefreshingText = @"暂无更多数据";
            }
            else
            {
            
            [_dataArray addObjectsFromArray:array];
                
            }
            
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
            
        }
        else
        {
            
            [self.tableView footerEndRefreshing];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataHandler removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
       
          [self.tableView footerEndRefreshing];
          [self.view makeToast:@"请检查网络"];
   
    }];

}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    if (self.dataArray.count == 0) {
        
        return 1;
    }
    return self.dataArray.count;


}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
 
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 0.00001;

}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 10;;
    
    
}
//
//
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
//    
//    view2.backgroundColor = BACKGROUND1;
//    
//    return view2;
//  
//}




-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
  
    if (self.dataArray.count == 0) {
        
        return emptyCellHeight;
    }
    else
    {
        CGFloat alertDiscussNumHeight = 0;
        CGFloat alertDiscussNumY = 8;
        CGFloat iconHeight = 34 / FDLaOt;
        CGFloat iconY = 16;
        CGFloat contentHeight = 0;
        CGFloat contentY = 8;
        CGFloat imageHeight;
        CGFloat imageY = 8;
        CGFloat addressImageY = 8;
        CGFloat addressImageHeight = 20 / FDLaOt;
        CGFloat bottomHeight = 8;
        CGFloat discussHeight = 0;
        CGFloat discussY = 8;
        
        NSArray *array = [NSArray arrayWithArray:self.dataArray[indexPath.section][@"friend_discuss"]];
        
        NSDictionary *dic = self.dataArray[indexPath.section];
        if ([self.dataArray[indexPath.section][@"discuss_count"] intValue] == 0) {
            
            discussY = 0;
            alertDiscussNumY = 0;
            alertDiscussNumHeight = 0;
        } else if ([self.dataArray[indexPath.section][@"discuss_count"] intValue] <= 3) {
            
            alertDiscussNumY = 0;
            alertDiscussNumHeight = 0;
        } else
            alertDiscussNumHeight = 17 / FDLaOt;
        
        NSString *discussStr;
        NSMutableArray *commentArray = [[NSMutableArray alloc] initWithCapacity:0];
        
        for (int i = 0; i < array.count; i ++) {
            
            if ([checkNull(array[i][@"pusername"]) length] == 0) {
                
                discussStr = [NSString stringWithFormat:@"%@：%@",[self getServiceStringAndReturnString:array[i][@"username"]],array[i][@"discuss"]];
            } else
                discussStr = [NSString stringWithFormat:@"%@ 回复 %@：%@",[self getServiceStringAndReturnString:array[i][@"username"]],[self getServiceStringAndReturnString:array[i][@"pusername"]],array[i][@"discuss"]];
            
            [commentArray addObject:discussStr];
        }
        
        if ([self.dataArray[indexPath.section][@"body"] length] == 0) {
            
            contentHeight = 0;
            contentY = 0;
        } else {
            
            CGSize releaseContentSize = [labelAdaptive sizeWithString:self.dataArray[indexPath.section][@"body"] font:[UIFont systemFontOfSize:13 / FDLaOt]];
            if (releaseContentSize.height <= 17 / FDLaOt * contentRow) {
                
                contentHeight = releaseContentSize.height;
            } else
                contentHeight = 17 / FDLaOt * contentRow;
        }
        
        NSString *string = self.dataArray[indexPath.section][@"imglist"];
        NSArray *imageArray;
        
        if (string.length < 5) {
            
            imageArray = [[NSArray alloc] init];
        } else {
            
            NSString *subString = @"|";
            imageArray = [string componentsSeparatedByString:subString];
        }
        
        CGSize imagesSize;
        
        if (imageArray.count > 0) {
            
            ShareListImageView *listImageView = [[ShareListImageView alloc] init];
            listImageView.images = imageArray;
            imagesSize = [listImageView sizeWithCount:(int)imageArray.count];
            imageHeight = imagesSize.height;
            
        } else {
            
            imageY = 0;
            imageHeight = 0;
        }
        
        for (int i = 0; i < commentArray.count; i ++) {
            
            NSString *discussStr = commentArray[i];
            CGFloat Height = 0;
            CGSize labelSize = [labelAdaptive sizeWithString:discussStr font:[UIFont systemFontOfSize:13 / FDLaOt]];
            if (labelSize.height <= 17 / FDLaOt * commentRow) {
                
                Height = labelSize.height;
            } else
                Height = commentRow * 17 / FDLaOt;
            
            discussHeight = discussHeight + Height + 8;
        }
        
        if (imageY == 0 && contentY == 0) {
            
            imageY = 8;
        }
        
        return discussY + discussHeight + bottomHeight + addressImageY + addressImageHeight + imageY + imageHeight + contentHeight + contentY + iconY + iconHeight + alertDiscussNumHeight + alertDiscussNumY;

    
        
    }

}


- (NSString *)getServiceStringAndReturnString:(NSString *)string {
    
    NSString *returnStr = [checkNull(string) length] > 0 ? string : @"";
    
    return returnStr;
}




-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    if (self.dataArray.count == 0) {
        
        
        self.emptyCell = [OMOrderEmptyTableViewCell cellWithTableView:self.tableView];
        self.emptyCell.selectionStyle = UITableViewCellSelectionStyleNone;
        cellHeight = [self.emptyCell setEmptyOrderCell];
        return self.emptyCell;
        
        
    }
    
    self.cell2 = [FruitLoopsCell cellWithTableView:tableView];
    
    self.cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    
//    NSDictionary *dict = _dataArray[indexPath.row];
    
     self.cell2.messageDic = self.dataArray[indexPath.section];
     self.cell2.delegate = self;
     NSString *string = self.dataArray[indexPath.section][@"imglist"];
    
    

    
    if (string.length < 5) {
        
        self.cell2.images = [[NSArray alloc] init];
        
        
    }
    else
    {
    
    NSString *subString = @"|";
    self.cell2.images = [string componentsSeparatedByString:subString];
    }
    
    cellHeight = [self.cell2 cellHeight];


    return self.cell2;
}
//图片放大显示
- (void)imageWithNames:(NSMutableArray *)array andIndex:(int)index {
    
    
    NSMutableArray *zImageArray = [[NSMutableArray alloc]initWithCapacity:0];
    EnlargeImageViewController *enlargeVC = [[EnlargeImageViewController alloc]init];
    
    //    UIImageView *imageView = [[UIImageView alloc] init];
    
    for (int i = 0; i < array.count; i++) {
        //        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ACURLiamge,array[i]]] placeholderImage:[UIImage imageNamed:@"timeline_image_placeholder"]];
        //        [zImageArray addObject:imageView.image];
        [zImageArray addObject:array[i]];
    }
    

    
    enlargeVC.imageArray = zImageArray;
    enlargeVC.pageIndex = index - 200;
    enlargeVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;    // 设置动画效果

    
    [self.parentViewController.tabBarController addChildViewController:enlargeVC];
    [self.parentViewController.tabBarController.view addSubview:enlargeVC.view];
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HPShareDetailsViewController *detailsVC = [[HPShareDetailsViewController alloc] initWithNibName:nil bundle:nil];
    detailsVC.fid = self.dataArray[indexPath.section][@"id"];
    detailsVC.messageDic = self.dataArray[indexPath.section];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushToSubControllerClick" object:nil userInfo:@{@"controller":detailsVC}];


    
//    [self.navigationController pushViewController:detailsVC animated:YES];
    
    
     [[NSNotificationCenter defaultCenter] postNotificationName:@"pushToSubControllerClick" object:nil userInfo:@{@"controller":detailsVC}];
}


@end
